<template>
  <div class="performance-monitor">
    <!-- 头部导航 -->
    <div class="header">
      <div class="header-left">
        <el-button @click="$router.push('/')" icon="ArrowLeft" circle />
        <h2>性能监控</h2>
      </div>

      <div class="header-right">
        <el-button @click="refreshReport" icon="Refresh" :loading="loading">
          刷新
        </el-button>
        <el-button @click="clearStatistics" type="warning" icon="Delete">
          清空统计
        </el-button>
        <el-button @click="checkBottleneck" type="danger" icon="Warning">
          检查瓶颈
        </el-button>
      </div>
    </div>

    <!-- 内容区域 -->
    <div class="content">
      <div v-if="loading" class="loading">
        <el-skeleton :rows="8" animated />
      </div>

      <div v-else-if="error" class="error">
        <el-alert
          title="加载失败"
          :description="error"
          type="error"
          show-icon
          @close="refreshReport"
        />
      </div>

      <div v-else class="performance-content">
        <!-- 性能报告 -->
        <el-card class="report-card" header="性能统计报告">
          <div class="report-content">
            <pre v-if="performanceReport">{{ performanceReport }}</pre>
            <el-empty v-else description="暂无性能数据" />
          </div>
        </el-card>

        <!-- 快速统计 -->
        <div class="quick-stats">
          <el-card header="常用步骤平均耗时">
            <div class="stats-grid">
              <div
                v-for="step in commonSteps"
                :key="step.name"
                class="stat-item"
                @click="getStepDetail(step.key)"
              >
                <div class="stat-icon">
                  <el-icon :color="step.color" size="24">
                    <component :is="step.icon" />
                  </el-icon>
                </div>
                <div class="stat-info">
                  <h4>{{ step.name }}</h4>
                  <p class="stat-value" v-if="stepAverages[step.key]">
                    {{ stepAverages[step.key].toFixed(1) }}ms
                  </p>
                  <p class="stat-value" v-else>-</p>
                </div>
              </div>
            </div>
          </el-card>
        </div>

        <!-- 详细信息 -->
        <el-card v-if="selectedStepDetail" class="detail-card" :header="`${selectedStepDetail.stepName} 详细信息`">
          <div class="step-detail">
            <el-descriptions :column="2" border>
              <el-descriptions-item label="步骤名称">{{ selectedStepDetail.stepName }}</el-descriptions-item>
              <el-descriptions-item label="平均耗时">{{ selectedStepDetail.averageTimeFormatted }}</el-descriptions-item>
            </el-descriptions>
          </div>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import {onMounted, reactive, ref} from 'vue'
import {useRouter} from 'vue-router'
import {ElMessage} from 'element-plus'
import {ChatDotSquare, DataAnalysis, Document, Microphone, VideoPlay} from '@element-plus/icons-vue'
import api from '@/api'

const router = useRouter()

// 响应式数据
const loading = ref(false)
const error = ref('')
const performanceReport = ref('')
const stepAverages = reactive<Record<string, number>>({})
const selectedStepDetail = ref<any>(null)

// 常用步骤配置
const commonSteps = [
  { key: '上传音频到OSS', name: 'OSS上传', icon: Microphone, color: '#409eff' },
  { key: 'ASR语音识别', name: 'ASR识别', icon: Microphone, color: '#67c23a' },
  { key: 'LLM生成回复', name: 'LLM对话', icon: ChatDotSquare, color: '#e6a23c' },
  { key: 'TTS语音合成', name: 'TTS合成', icon: VideoPlay, color: '#f56c6c' },
  { key: '保存用户消息', name: '保存消息', icon: Document, color: '#909399' },
  { key: '构建对话上下文', name: '构建上下文', icon: DataAnalysis, color: '#606266' }
]

// 组件挂载时加载数据
onMounted(() => {
  refreshReport()
  loadStepAverages()
})

// 刷新性能报告
const refreshReport = async () => {
  try {
    loading.value = true
    error.value = ''

    const response = await api.get('/performance/report')
    performanceReport.value = response.data
  } catch (err) {
    error.value = '网络错误，请检查后端服务是否启动'
    console.error('获取性能报告失败:', err)
  } finally {
    loading.value = false
  }
}

// 加载步骤平均耗时
const loadStepAverages = async () => {
  for (const step of commonSteps) {
    try {
      const response = await api.get(`/performance/step-average/${encodeURIComponent(step.key)}`)
      stepAverages[step.key] = response.data.averageTimeMs
    } catch (error) {
      console.error(`获取步骤 ${step.key} 平均耗时失败:`, error)
    }
  }
}

// 获取步骤详情
const getStepDetail = async (stepKey: string) => {
  try {
    const response = await api.get(`/performance/step-average/${encodeURIComponent(stepKey)}`)
    selectedStepDetail.value = response.data
  } catch (error) {
    console.error('获取步骤详情失败:', error)
    ElMessage.error('获取步骤详情失败')
  }
}

// 清空统计数据
const clearStatistics = async () => {
  try {
    const response = await api.post('/performance/clear')
    await refreshReport()
    await loadStepAverages()
  } catch (error) {
    console.error('清空统计数据失败:', error)
    ElMessage.error('清空失败')
  }
}

// 检查性能瓶颈
const checkBottleneck = async () => {
  try {
    const response = await api.post('/performance/check-bottleneck')
    ElMessage.success('性能瓶颈检查完成，请查看控制台日志')
  } catch (error) {
    console.error('检查性能瓶颈失败:', error)
    ElMessage.error('检查失败')
  }
}
</script>

<style scoped>
.performance-monitor {
  min-height: 100vh;
  background: #f5f6fa;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  background: white;
  border-bottom: 1px solid #e9ecef;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.header-left h2 {
  margin: 0;
  color: #2c3e50;
}

.header-right {
  display: flex;
  gap: 12px;
}

.content {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.loading, .error {
  background: white;
  border-radius: 12px;
  padding: 40px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
}

.performance-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.report-card {
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
}

.report-content {
  max-height: 400px;
  overflow-y: auto;
}

.report-content pre {
  background: #f8f9fa;
  padding: 16px;
  border-radius: 8px;
  font-family: 'Courier New', monospace;
  font-size: 0.9rem;
  line-height: 1.4;
  margin: 0;
  white-space: pre-wrap;
}

.quick-stats {
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 16px;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.stat-item:hover {
  background: #e9ecef;
  transform: translateY(-2px);
}

.stat-icon {
  flex-shrink: 0;
}

.stat-info {
  flex: 1;
}

.stat-info h4 {
  margin: 0 0 4px 0;
  font-size: 0.9rem;
  color: #2c3e50;
}

.stat-value {
  margin: 0;
  font-size: 1.2rem;
  font-weight: bold;
  color: #409eff;
}

.detail-card {
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
}

.step-detail {
  padding: 16px 0;
}

@media (max-width: 768px) {
  .header {
    padding: 16px;
    flex-direction: column;
    gap: 16px;
  }

  .header-right {
    flex-wrap: wrap;
  }

  .content {
    padding: 16px;
  }

  .stats-grid {
    grid-template-columns: 1fr;
  }
}
</style>
